package com.ferris.redbook.config;

import com.ferris.redbook.interceptor.JwtAuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.Paths;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private JwtAuthenticationInterceptor jwtAuthenticationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtAuthenticationInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/auth/login",          // 只排除登录接口
                        "/auth/register",       // 只排除注册接口
                        "/api/uploads/**",      // 排除静态资源访问
                        "/swagger-ui/**",
                        "/v3/api-docs/**",
                        "/uploads/avatars/**",
                        "/uploads/images/**",
                        "/users/*/posts"
                         );
    }

    @Value("${app.upload.base-path}")
    private String uploadBasePath;

    @Value("${app.storage.images-dir}")
    private String imagesDir;

    @Value("${app.storage.avatars-dir}")
    private String avatarsDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射图片目录
        String imagesPath = Paths.get(uploadBasePath, imagesDir).toAbsolutePath().toUri().toString();
        registry.addResourceHandler("/uploads/images/**")
                .addResourceLocations(imagesPath);

        // 映射头像目录
        String avatarsPath = Paths.get(uploadBasePath, avatarsDir).toAbsolutePath().toUri().toString();
        registry.addResourceHandler("/uploads/avatars/**")
                .addResourceLocations(avatarsPath);
    }
}